package com.hhd.flow.engine.cmd.impl;

import com.hhd.flow.engine.cmd.PassTaskContext;
import com.hhd.flow.engine.utils.CommonUtils;
import com.hhd.flow.engine.vo.FlowUser;
import com.hhd.flow.engine.vo.UserTask;
import com.hhd.flow.entity.FlowProcessInstance;
import com.hhd.flow.entity.FlowUserTask;
import com.hhd.flow.exception.FlowException;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.SuperBuilder;

import java.util.List;

@Setter
@Getter
@SuperBuilder(toBuilder = true)
public class QueryNotifyFlowUserCommand extends BaseCommand<List<FlowUser>> {
    UserTask userTask;
    String flowUserTaskId;

    //下面是运行时产生的数据
    private FlowUserTask flowUserTask;
    PassTaskContext context;
    FlowProcessInstance flowProcessInstance;

    @Override
    public List<FlowUser> execute() {
        flowUserTask = getEngine().getFlowUserTaskService().getById(flowUserTaskId);
        CommonUtils.isEmptyThrow(flowUserTask, new FlowException("没有找到用户任务: " + flowUserTaskId + "请刷新页面后重试"));
        createContext();
        return getEngine().loadFlowUser(flowUserTask.getFormTypeId(), flowUserTask.getFormId(), userTask, context);
    }

    private void createContext() {
        flowProcessInstance = getEngine().getFlowProcessInstanceService().getById(flowUserTask.getProcessInstanceId());
        context = PassTaskContext.builder()
                .variablesContainer(getVariablesContainer(flowUserTask.getFormTypeId(), flowUserTask.getFormId(), flowProcessInstance, null))
                .formTypeId(flowUserTask.getFormTypeId())
                .formId(flowUserTask.getFormId())
                .flowTaskId(flowUserTask.getTaskInstanceId())
                .flowProcessInstanceId(flowUserTask.getProcessInstanceId())
                .userManualSelect(null)
                .formModel(null)
                .build();
    }
}
